package cn.icatw.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author icatw
 * @date 2022/3/25
 * @email 762188827@qq.com
 * @apiNote
 */
@Configuration
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、RequestAttributes拿到进来的request请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //老请求，本地请求
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    //同步请求头数据，cookie
                    String cookie = request.getHeader("Cookie");
                    //给新请求同步cookie
                    template.header("Cookie", cookie);
                    System.out.println("feign远程调用之前先进行requestInterceptor.apply");
                }
            }
        };
    }
}
